<?php
namespace App\Console\Commands;

use App\Models\Achievement;
use App\Models\Attendance;
use App\Models\Keys;
use App\Models\RewardPunishDetail;
use Illuminate\Console\Command;

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use App\Models\UserPerformance;
use App\Models\UserPerformanceMonth;


class Tongji extends Command
{
    protected $signature = 'tongji';
    
    protected $description = '统计用户绩效总分';
    
    public function __construct()
    {
        parent::__construct();
    }
    
    public function handle()
    {
       /* $key = Keys::where('name','userid')->first();
        if(empty($key)){
            $key = new Keys();
            $key->name = 'userid';
            $key->value = 0;
            $key->save();
        }
        $current = isset($key->value)?$key->value:'0';
        $perf = UserPerformance::where('id','>',$current)->limit('300')->get();
        if(count($perf) == 0){
            $key->value = 0;
            $key->save();
            die();
        }else{
            $key->value = $current+300;
            $key->save();
            foreach ($perf as $p){
                $standard_t = Achievement::where('corpid',$p->corpid)->where('user_id',$p->user_id)->sum('standard');
                $score_t = Achievement::where('corpid',$p->corpid)->where('user_id',$p->user_id)->sum('score');
                if($standard_t == 0){
                    $gg = 0;
                }else{
                    $gg =  round($score_t/$standard_t,2)*100;
                    $gg = intval($gg);
                }

                $kq_score = Attendance::where('corpid',$p->corpid)->where('user_id',$p->user_id)->sum('score');

                $reward = RewardPunishDetail::where('corpid',$p->corpid)->where('to_user_id',$p->user_id)->where('is_effective','1')->where('kind','1')->sum('score');
                $punish = RewardPunishDetail::where('corpid',$p->corpid)->where('to_user_id',$p->user_id)->where('is_effective','1')->where('kind','2')->sum('score');
                $p->jiangcheng = $reward + $punish;
                $p->kaoqin = $kq_score;
                $p->yeji = $gg;
                $p->total = $gg + $kq_score+ $reward + $punish;
                $p->save();

                //存入上月数据,粗略
                $last_month = date("Ym",strtotime("-1 month",time()));
                $day = date("d",time());
                if($day == '1'){
                    $last = new UserPerformanceMonth();
                    $last->month = $last_month;
                    $last->corpid = $p->corpid;
                    $last->user_id = $p->user_id;
                    $last->kaoqin = $p->kaoqin;
                    $last->yeji = $p->yeji;
                    $last->jiangcheng = $p->jiangcheng;
                    $last->total = $p->total;
                    $last->save();
                }
            }
            exec('php /data/webroot/kaohe/artisan tongji');
        }

        Log::info(['统计顺利完成'=>'success']);*/
    }
}

